#pragma once
#include "Log.hpp"
#include "data.hpp"
#include "httplib.h"
#include <windows.h>

namespace my_cloud {
#define SERVER_IP "101.33.203.127"
#define SERVER_PORT 8080
	class Backup {
	private:
		std::string _back_dir;
		DataManager* _data;
	public:
		Backup(const std::string& back_dir, const std::string& backup_file) : _back_dir(back_dir) {
			_data = new DataManager(backup_file);
		}

		std::string GetFileIdentifier(const std::string& filename) {
			std::stringstream ss;
			FileUtil fu(filename);
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.FileMTime();
			return ss.str();
		}

		bool Upload(const std::string& filename) {
			FileUtil fu(filename);
			std::string content;
			fu.GetContent(content);

			httplib::Client client(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormData item;
			item.content = content;
			item.content_type = "application/octet-stream";
			item.filename = fu.FileName();
			item.name = "file";
			httplib::MultipartFormDataItems items;
			items.push_back(item);

			auto res = client.Post("/upload", items);
			if (!res || res->status != 200) {
				return false;
			}
			return true;
		}

		bool IsNeedUpload(const std::string& filename) {
			std::string id;
			if (_data->GetOneByKey(filename, &id) != false) {
				std::string new_id = GetFileIdentifier(filename);
				if (new_id == id) {
					return false;
				}
			}

			FileUtil fu(filename);
			if (time(NULL) - fu.FileMTime() < 3) {
				return false;
			}

			LOG(INFO, filename + " Need Upload!");
			return true;
		}

		bool RunModule() {
			while (1) {
				std::cout << "-----------------load begin------------------" << std::endl;
				FileUtil fu(_back_dir);
				std::vector<std::string> arry;
				fu.ScanDir(arry);
				for (auto& file : arry) {
					if (IsNeedUpload(file) == false) {
						continue;
					}
					if (Upload(file) == true) {
						_data->Insert(file, GetFileIdentifier(file));
						LOG(INFO, file + " Upload Success!");
					}
				}
				Sleep(3);
				std::cout << "-----------------load begin------------------" << std::endl;
			}
		}
	};
}
